package leetcode.多线程;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author :songyaozhang
 * @date :Created 2021/8/16 13:43
 * @description :
 */
public class printABC {
    public static void main(String[] args) {
        Date date = new Date();
        new Thread(() -> {while(true) date.printA();}).start();
        new Thread(() -> {while(true) date.printB();}).start();
        new Thread(() -> {while(true) date.printC();}).start();
    }

    static class Date {
        private int num = 1;
        private Lock lock = new ReentrantLock();
        private Condition A = lock.newCondition();
        private Condition B = lock.newCondition();
        private Condition C = lock.newCondition();

        public void printA() {
            lock.lock();
            try {
                while (num != 1) {
                    A.await();
                }
                System.out.print("A");
                num = 2;
                B.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        public void printB() {
            lock.lock();
            try {
                while (num != 2) {
                    B.await();
                }
                System.out.print("B");
                num = 3;
                C.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        public void printC() {
            lock.lock();
            try {
                while (num != 3) {
                    C.await();
                }
                System.out.print("C");
                num = 1;
                A.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
